package com.g0dkar.leet.core;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.jdom.Element;

import com.g0dkar.leet.core.configuration.LeetConfiguration;
import com.g0dkar.leet.core.configuration.loaders.LeetConfigurationClassLoader;
import com.g0dkar.leet.core.configuration.loaders.LeetConfigurationPropertiesLoader;
import com.g0dkar.leet.core.configuration.loaders.LeetConfigurationXmlLoader;
import com.g0dkar.leet.exception.LeetRuntimeException;
import com.g0dkar.leet.util.file.FileUtils;
import com.g0dkar.leet.util.file.XMLUtils;

/**
 * A {@link Runnable} class that initializes a {@link Leet} object, which is the heart of a Leet Framework Application.
 * This class is probably <strong>not</strong> Thread Safe.
 * 
 * @author g0dkar
 * 
 */
public class LeetStartup implements Runnable {
	private Leet leet;
	
	public LeetStartup(Leet leet) {
		this.leet = leet;
	}
	
	public void run() {
		if (leet != null) {
			Leet.INSTANCE = leet;
			LeetConfiguration configuration = null;
			
			String configFile = "/leet-configuration.xml";
			File configXml = FileUtils.getFile(configFile);
			if (configXml != null) {
				Element root = XMLUtils.parse(configFile);
				LeetConfigurationXmlLoader xmlLoader = new LeetConfigurationXmlLoader();
				configuration = xmlLoader.load(root);
			}
			
			File propertiesFile = FileUtils.getFile("/leet.properties");
			if (propertiesFile != null) {
				Properties properties = new Properties();
				
				try {
					properties.load(new FileInputStream(propertiesFile));
				} catch (Exception e) {
					throw new LeetRuntimeException("Could not initialize this Leet Framework Application through the leet.properties file.", e);
				}
				
				LeetConfigurationPropertiesLoader propertiesLoader = new LeetConfigurationPropertiesLoader();
				configuration = propertiesLoader.load(properties);
			}
			
			if (configuration == null) {
				LeetConfigurationClassLoader classLoader = new LeetConfigurationClassLoader();
				configuration = classLoader.load(configuration);
			}
			
			leet.setConfiguration(configuration);
		}
	}
}
